package com.youlu.campus.service.platform.impl;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.entity.PointPlatformConfig;
import com.youlu.campus.entity.VO.req.PlatformTaskQueryVO;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.entity.platform.PlatformTaskInfo;
import com.youlu.campus.service.platform.PlatformTaskService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 获取平台级任务列表服务实现类
 */
@Service
@Slf4j
public class PlatformTaskServiceImpl implements PlatformTaskService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public Page<PlatformTaskInfo> getTaskList(PlatformTaskQueryVO req) {
        Query query = new Query();
        query.addCriteria(Criteria.where("appId").is(req.getAppId()));
        if (StringUtils.isNotBlank(req.getPlatform())) {
            query.addCriteria(Criteria.where("platform").is(req.getPlatform()));
        }
        long count = mongoTemplate.count(query, PlatformTaskInfo.class);
        PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<PlatformTaskInfo> infos = mongoTemplate.find(query.with(pageRequest), PlatformTaskInfo.class);
        return PageableExecutionUtils.getPage(infos, pageRequest, () -> count);
    }

    @Override
    public Map<TaskBizType, List<String>> findPlatformByAppId(String appId,String platform) {
        Query query = new Query();
        query.addCriteria(Criteria.where("appId").is(appId));
        query.addCriteria(Criteria.where("platform").is(platform));
        List<PlatformTaskInfo> list = this.mongoTemplate.find(query, PlatformTaskInfo.class);
        if(CollectionUtils.isEmpty(list)){
            return new HashMap<>();
        }
        Map<TaskBizType, List<String>> result  = new HashMap<>(list.size());
        list.stream().forEach(platformTaskInfo -> {
            result.put(platformTaskInfo.getTaskBizType(),platformTaskInfo.getTaskExtra());
        });
        return result;
    }
}
